package com.liumuxian.video.web.controller;

import com.liumuxian.video.config.ServerConfig;
import com.liumuxian.video.pojo.Resource;
import com.liumuxian.video.service.ResourceService;
import entity.*;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.*;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import util.UploadFileUtil;
import java.io.*;
import java.util.*;

@RestController

public class ResourceController {
    @Autowired
    private ResourceService resourceService;
    @Value("${file.uploadFolder}")
    private String uploadFolder;
    @Autowired
    private ServerConfig serverConfig;

    /**
     * 上传多个文件 添加
     * @param file
     * 上传文件集合
     * @return
     */
    @PostMapping(value = "/uploadfile")
    public Result uploads(@PathVariable MultipartFile[] file) {

        List<String> fileUrl = new ArrayList<>();
        List<Resource> resourceList = new ArrayList<>();
        try {
            //上传目录地址
            Calendar cal = Calendar.getInstance();
            String year = cal.get(Calendar.YEAR) + "";
            //比当前月份少1
            String month = cal.get(Calendar.MONTH) + 1 + "";
            //date表示日期，day表示天数，所以date与day_of_month相同
            String date = cal.get(Calendar.DATE) + "";
            /* uploadFolder = uploadFolder+year+"\\"+month+"\\"+date;*/
            String feilPath = uploadFolder + year + "/" + month + "/" + date;
            String urlPath = serverConfig.getUrl() + "/" + year + "/" + month + "/" + date + "/";
            if (!new File(feilPath).exists()) {
                new File(feilPath).mkdirs();
            }
            //遍历文件数组执行上传
            for (int i = 0; i < file.length; i++) {
                if (file[i] != null) {
                    Resource resource = new Resource();
                    String url = urlPath + UploadFileUtil.executeUpload(feilPath, file[i]);
                    //调用上传方法
                    fileUrl.add(url);
                    resource.setPath(url);
                    resource.setName(file[i].getName());
                    resourceList.add(resource);
                }
            }
            resourceService.saveAll(resourceList);
        } catch (Exception e) {
            //打印错误堆栈信息
            e.printStackTrace();
            throw new RuntimeException("上传失败！");
        }
        System.out.println(fileUrl);
        return new Result(true,StatusCode.OK,"上传成功！",fileUrl);
    }

    /**
     * 添加
     * @param resource
     * @param file
     * @return
     * @throws IOException
     */
    @RequestMapping("resourceAdd")
    public Result add(Resource resource, @RequestParam(value = "file", required = true) MultipartFile file) throws IOException{
        byte[] bytes = file.getBytes();
        String year = DateTime.now().toString("yyyy")+"\\"+DateTime.now().toString("MM")+"\\"+DateTime.now().toString("dd");
        //Office OFFICE功能模块、Accountant 会计考证功能模块、Teacher 教师资格证功能模块、SoftTest 软考功能模块
        String sub[]={"Office","Accountant","Teacher","SoftTest"};
        String uploadFolder=this.uploadFolder+sub[0]+"\\"+year;
        File fileToSave = new File(uploadFolder+"\\",file.getOriginalFilename());
        if(!fileToSave.getParentFile().exists()){//判断服务器当前路径文件夹是否存在
            fileToSave.getParentFile().mkdirs();//不存在则创建文件夹
        }
        FileCopyUtils.copy(bytes, fileToSave);
        resource.setType(0);
        resource.setPath(file.getOriginalFilename());
        resourceService.save(resource);
        return new Result(true, StatusCode.OK,  "保存成功",resource);
    }

    /**
     * 删除
     * @param rid
     * @return
     */
    @RequestMapping("resourceDelete/{rid}")
    public Result delete(@PathVariable String rid){
        Resource resource=resourceService.getOne(rid);
        resource.setState(0);
        resourceService.update(resource);
        return new Result(true, StatusCode.OK,  "删除成功",resource);
    }

    /**
     * 修改
     * @param resource
     * @return
     */
    @RequestMapping("resourceUpdate")
    public Result update(Resource resource){
        resource.setId("1205410591221616640");
        resource.setName("李四");
        resource.setState(0);
        resource.setCreatdata(new Date());
        resource.setUpdatedate(new Date("2020/01/01"));
        resourceService.update(resource);
        return new Result(true, StatusCode.OK,  "修改成功",resource);
    }

    /**
     * 根据id查询
     * @param rid
     * @return
     */
    @RequestMapping("resourceFindById/{rid}")
    public Result findById(@PathVariable String rid){
        Resource r=resourceService.getOne(rid);
        return new Result(true, StatusCode.OK,  "查询成功",r);
    }

    /**
     * 查询全部
     * @return
     */
    @RequestMapping("resourceFindAll")
    public Result findAll(){
        List<Resource> list=resourceService.findAllByState(1);
        for (Resource r:list) {
            System.out.println(r.toString());
        }
        return new Result(true, StatusCode.OK,  "查询成功",list);
    }

    public static void main(String[] args) {
        System.out.println();
    }
}
